import { Injectable } from '@nestjs/common';
import Redis from 'ioredis'



@Injectable()
export class BaseCacheService {
    protected Client : Redis

    get client() {
        return this.Client
    }

    set(key:string, value:string | Buffer | number) : Promise<boolean>;
    set(key:string, value:string | Buffer | number, ttl : number) : Promise<boolean>;
    set(key:string, value:string | Buffer | number, nx: "NX") : Promise<boolean>;
    set(key:string, value:string | Buffer | number, seconds: number, nx: "NX") : Promise<boolean>;
    

    async set(...args:any[]) : Promise<boolean>{
        let res
        let argsLen = args.length
        if(argsLen == 2) {
            res = await this.Client.set(args[0], args[1])
        }else if(argsLen == 3) {
            res = await this.Client.set(args[0], args[1], 'EX', args[2])
        }else if(argsLen == 4) {
            res = await this.Client.set(args[0], args[1], 'EX', args[2], 'NX')
        }

        return res === 'OK'
    }

    pop(key:string) {
        return this.Client.rpop(key)
    }

    get(key:string) {
        return this.Client.get(key)
    }

    del(...keys:string[]) : Promise<number>{
        return this.Client.del(...keys)
    }

    blpop(key:string, timeout:number) {
        return this.Client.blpop(key, timeout)
    }

    async blockLock(key:string, timeout:number) {
        const len = await this.Client.llen(key)
        if(len == 0) { //还没有这个队列
            const rs = await this.set(key + ':nx', '1', timeout + 3, 'NX')
            if(rs) { //获得锁
                return true
            }
        }

        const res = await this.blpop(key, timeout)
        return res ? true : false
    }

    async unBlockLock(key:string) {
        this.Client.lpush(key, '1')
    }

    hmset(key:string, data:{[key:string] : string|number}) {
        this.Client.hmset(key, data)
    }

    hgetall(key:string) {
        return this.Client.hgetall(key)
    }
    
}
